﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Generator.Selections.DataDictionary;
using Generator.Selections.Windows;
using Manor.CslaDesigner.DslPackage.CustomCode;
using Microsoft.VisualStudio.Modeling.Shell;

namespace Manor.CslaDesigner
{
    /// <summary>
    /// Double-derived class to allow easier code customization.
    /// </summary>
    internal partial class CslaDesignerCommandSet
    {
        private List<Table> _tables;
        private string _nameSpace;
        private readonly Guid _guidShowTablesCmdSet =
               new Guid("335770B0-268F-4790-A208-9D3FF55DA8D7");
        //private const int GrpidShowTablesGroup = 0x01001;
        private const int CmdidShowTablesContextMenuCommand = 1;

        private void OnStatusShowTablesCommand(object sender, EventArgs e)
        {
            var command = sender as MenuCommand;

            if (command != null)
                command.Visible = command.Enabled = IsDiagramSelected();
        }

        private void OnMenuShowTablesMenuCommand(object sender, EventArgs e)
        {
            AskForTables();
            CreateModelClass();
        }

        private void CreateModelClass()
        {
            if (_tables== null) return;

            var modelRoot = CurrentCslaDesignerDocData.RootElement as ModelRoot;
            var classManager = new ModelClassManager(modelRoot, _tables, _nameSpace);
            classManager.AddModelClassesWithAssociations();
            classManager.AdjustNewModelClassPosition();
        }

        private void AskForTables()
        {
            var startGeneratorSelection = new StartGeneratorSelection
                {
                    NameSpace = "Company.Business." + CurrentDocView.CurrentDiagram.Name
                };

            startGeneratorSelection.Execute();

            _tables = startGeneratorSelection.SelectedTables;
            _nameSpace = startGeneratorSelection.NameSpace;
        }

        protected override IList<MenuCommand> GetMenuCommands()
        {
            var commands = base.GetMenuCommands();

            var myContextMenuCommand =
              new DynamicStatusMenuCommand(
                OnStatusShowTablesCommand,
                OnMenuShowTablesMenuCommand,
                new CommandID(_guidShowTablesCmdSet, CmdidShowTablesContextMenuCommand));

            commands.Add(myContextMenuCommand);

            return commands;
        } 

    }
}